package controllers

import (
	"cms/common"
	"cms/model"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"github.com/kataras/iris/sessions"
	"strconv"
)

type ApplyController struct {
	Ctx     iris.Context
	Session *sessions.Session
	Apply   model.Apply
}

func (c *ApplyController) Get() mvc.View {
	page, err := strconv.Atoi(c.Ctx.URLParam("page"))
	if err != nil || page < 1 {
		page = 1
	}
	list, total, totalPages := c.Apply.List(page)
	return mvc.View{
		Name:   "apply/list.html",
		Layout: "shared/layout.html",
		Data: iris.Map{
			"Title":    "内容列表",
			"list":     list,
			"PageHtml": commons.GetPageHtml(totalPages, page, total, c.Ctx.Path()),
		},
	}
}

func (c *ApplyController) GetAdd() mvc.View {
	return mvc.View{
		Name:   "apply/add.html",
		Layout: "shared/layout.html",
		Data: iris.Map{
			"Title": "新增内容",
		},
	}
}

func (c *ApplyController) PostAdd() {
	if err := c.Apply.Add(c.Ctx.FormValues()); err == nil {
		c.Ctx.Redirect("/apply")
	} else {
		commons.DefaultErrorShow(err.Error(), c.Ctx)
	}
}

func (c *ApplyController) GetUpdateBy(id uint) mvc.View {
	ApplyInfo, err := c.Apply.Info(id)
	if err != nil {
		return commons.MvcError(err.Error(), c.Ctx)
	}
	Category := model.Category{}
	list := Category.List()
	model.ListTree = []model.Category{}
	list = Category.GetTree(list, 0, 0)

	Re := model.Recommend{}
	ReList := Re.ListAll()

	return mvc.View{
		Name:   "apply/update.html",
		Layout: "shared/layout.html",
		Data: iris.Map{
			"Title":      "内容修改",
			"UpdateInfo": ApplyInfo,
			"list":       list,
			"ReList":     ReList,
		},
	}
}

func (c *ApplyController) PostUpdate() {
	if err := c.Apply.Update(c.Ctx.FormValues()); err == nil {
		c.Ctx.Redirect("/apply")
	} else {
		commons.DefaultErrorShow(err.Error(), c.Ctx)
	}
}

func (c *ApplyController) GetDelBy(id uint) {
	if err := c.Apply.Del(id); err == nil {
		c.Ctx.Redirect("/apply")
	} else {
		commons.DefaultErrorShow(err.Error(), c.Ctx)
	}
}
